package com.itzz.spring_zhoneHeng.config;

import com.itzz.spring_zhoneHeng.base.JwtTokenUtils;
import com.itzz.spring_zhoneHeng.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtFile extends OncePerRequestFilter {
    @Autowired
    MyUserDetailsService myUserDetailsService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 1.获取请求头中的token 判断是否为"Authorization"
        String header = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        // 2.如果存在token 则判断是否存在"Bearer"
        if(header!=null&&header.startsWith(JwtTokenUtils.TOKEN_PREFIX)){
            // 3.如果存在token 则将"Bearer" 替换成 ""
            String jwt = header.replace(JwtTokenUtils.TOKEN_PREFIX, "");
            // 4.判断token是否存在 并且是否过期
            if(jwt!=null&&JwtTokenUtils.isExpiration(jwt)){
                // 5.jwt未过期获取用户名重新走一遍 登录逻辑获取用户信息保存在Security全局域中
                String username = JwtTokenUtils.getTokenName(jwt);
                UserDetails userDetails = myUserDetailsService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

                //保存在全局域中
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }

        //放行所有请求和响应
        filterChain.doFilter(request,response);
    }
}
